<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
    @close="jkeModalUpdate"
  >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="menus" currentMenu="申请发货"></crumbs>
    <div class="form-body">
      <a-card title="基本信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="客户名称">
            <a-select
              v-decorator="['customerId', { rules: [{ required: true, message: '请选择客户名称' }] }]"
              placeholder="请选择客户名称"
              @change="handleSelectCustomer"
            >
              <a-select-option v-for="item in customerList" :key="item.id" :value="item.id">
                {{ item.customerFullName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="销售合同">
            <a-select
              v-decorator="['contractId', { rules: [{ required: true, message: '请选择销售合同' }] }]"
              placeholder="请选择销售合同"
              @change="handleSelectContract"
            >
              <a-select-option v-for="item in contractList" :key="item.id" :value="item.id">
                {{ item.contractName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="承诺交期">
            <a-input placeholder="请先选择销售合同" disabled v-decorator="['promiseDate']" />
          </a-form-item>
        </a-form>
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="领用人">
            <j-select-user-by-dep
              @changeRow="selectUser"
              v-decorator="['receiveBy', { rules: [{ required: true, message: '请选择领用人' }] }]"
              :seldep="true"
              :modalWidth="1000"
              :multi="false"
            ></j-select-user-by-dep>
          </a-form-item>
          <a-form-item label="发货日期">
            <j-date
              style="width: 100%"
              placeholder="请选择"
              v-decorator="['shippingDate', { rules: [{ required: true, message: '请选择发货日期' }] }]"
            ></j-date>
          </a-form-item>
          <a-form-item label=""></a-form-item>
        </a-form>
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="发货备注" style="flex: 1">
            <a-textarea
              placeholder="请输入"
              :rows="4"
              :maxLength="500"
              v-decorator="['remark', { rules: [{ message: '请输入发货备注' }] }]"
            />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="发货明细" :bordered="false" style="margin-top: 12px">
        <a-table
          row-key="id"
          :columns="columns"
          :data-source="tableData"
          :pagination="false"
          :scroll="{ x: '100%', y: 'calc(100vh - 366px)' }"
          :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle: ' ', onChange: onSelectChange }"
          @change="handleChange"
        >
          <span slot="shippedNumTitle" style="color: #f25643">*本次发货数量</span>
          <span
            slot="shippedNum"
            slot-scope="text, record, index"
            :title="`${record.shippedNum || ''} ${record.unit || ''}`"
          >
            <a-input
              v-model="record.shippedNum"
              @blur="(e) => blur(e, index)"
              @change="(e) => inputChange(e, index)"
              @focus="inputFocus(record)"
              placeholder="请输入"
            >
              <div slot="suffix" style="background: #fff">
                {{ record.unit ? subStrText(record.unit, 3) : '' }}
              </div>
            </a-input>
          </span>
          <span :title="text" slot="goodsName" slot-scope="text">
            {{ subStrText(text, 6) }}
          </span>
          <span :title="text" slot="shippingNum" slot-scope="text, record"> {{ text }}{{ record.unit }} </span>
          <span :title="text" slot="saleBasicNum" slot-scope="text, record"> {{ text }}{{ record.basicUnit }} </span>
          <span :title="text" slot="saleNum" slot-scope="text, record"> {{ text }}{{ record.unit }} </span>

          <span slot="picUrl" slot-scope="text">
            <img :src="text" alt="" class="imgClass" />
          </span>
          <span slot="action" slot-scope="text, record">
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDelete(record)">删除</a>
          </span>
        </a-table>
        <!-- 全选/分页 -->
        <div style="padding-top: 24px; margin-left: 28px">
          <a-checkbox
            :indeterminate="listIndeterminate"
            :checked="listCheckAll"
            @change="onCheckAllChange"
          ></a-checkbox>
          <!-- <span class="pubColor" style="margin: 0 24px">批量完成</span><span class="pubColor">批量作废</span> -->
          <span style="margin-left: 8px">
            {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
            <span @click="clearArr" class="pubColor" style="margin: 0 10px">清空</span>
          </span>
        </div>
      </a-card>
      <div style="margin: 12px 0 24px">
        <Examine @submitProcess="submitProcess" type="0" id="ERP_SHIPPING_APPLY" ref="examine" />
        <div style="height: 50px"></div>
      </div>
    </div>
    <div class="footer-submit form-footer">
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button type="primary" class="submitBtn" :loading="loadingSubmit" @click="submitProcess"> 提交 </a-button>
    </div>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import { getFileListByIds } from '@/api/api'
import { numFormat, subStrText, fourFloatNum } from '@/utils/util'
import { APILX } from '@/api/requestLx'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import Examine from '@/components/examine'
import { apiBaseUrlDownload } from '@/utils/request'
export default {
  name: 'applyDeliver', //申请发货
  data() {
    return {
      jkeForm: {
        title: '申请发货',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      menus: ['首页'],
      domianURL: apiBaseUrlDownload,
      customerList: '', //下拉客户数据
      contractList: '', //下拉合同数据
      fourFloatNum,
      subStrText,
      total: 0,
      numFormat,
      selectedRowKeys: [],
      selectedRows: [],
      selectArr: [],
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      tableData: [],
      // table
      columns: [
        {
          title: '商品图片',
          dataIndex: 'picUrl',
          width: 160,
          key: 'picUrl',
          ellipsis: true,
          scopedSlots: {
            // filterDropdown: 'searchInput',
            // filterIcon: 'searchIcon',
            customRender: 'picUrl',
          },
        },
        {
          title: '商品编号',
          dataIndex: 'goodsCode',
          key: 'goodsCode',
          width: 160,
          ellipsis: true,
          scopedSlots: {
            // filterDropdown: 'searchInput',
            // filterIcon: 'searchIcon',
            customRender: 'goodsCode',
          },
        },
        {
          title: '商品名称',
          dataIndex: 'goodsName',
          key: 'goodsName',
          width: 160,
          ellipsis: true,
          scopedSlots: {
            // filterDropdown: 'searchInput',
            // filterIcon: 'searchIcon',
            // customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          width: 160,
          dataIndex: 'spec',
          key: 'spec',
          ellipsis: true,
        },
        {
          title: '订购数量',
          dataIndex: 'saleNum',
          width: 160,
          key: 'saleNum',
          ellipsis: true,
          scopedSlots: {
            customRender: 'saleNum',
          },
        },
        {
          title: '订购基本数量',
          dataIndex: 'saleBasicNum',
          key: 'saleBasicNum',
          width: 160,
          ellipsis: true,
          scopedSlots: {
            customRender: 'saleBasicNum',
          },
        },
        {
          title: '已申请发货数量',
          dataIndex: 'shippingNum',
          width: 160,
          key: 'shippingNum',
          ellipsis: true,
          scopedSlots: {
            customRender: 'shippingNum',
          },
        },
        {
          // title: '*本次发货数量',
          slots: { title: 'shippedNumTitle' },
          width: 160,
          dataIndex: 'shippedNum',
          key: 'shippedNum',
          scopedSlots: {
            customRender: 'shippedNum',
          },
        },
      ],
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      loadingSubmit: false, //防止多次提交
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
      imgurlArr: [],
      receiveById: '', // 领用人id
    }
  },
  components: {
    FileUpload,
    crumbs,
    Examine,
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  methods: {
    jkeModalUpdate() {
      if (this.$route.path == '/dashboard/analysis') {
        this.$store.commit('SET_CURRENT_PREFIX','/jksaas-mgt/mgt')
      }
    },
    initForm(query) {
      this.$store.commit('SET_CURRENT_PREFIX','/jksaas-produce/produce')
      this.jkeForm.visible = true
      /* ----------销售合同列表申请发货带入客户、合同、日期信息begin---------- */
      if (query.dealInfo) {
        console.log('----------销售合同列表申请发货带入客户、合同、日期信息begin----------');
        this.menus = ['销售管理', '销售合同']
        let dealInfo = JSON.parse(query.dealInfo)
        this.customerList = [{ customerFullName: dealInfo.customerIdText, id: dealInfo.customerId }]
        this.contractList = [{ contractName: dealInfo.contractName, id: dealInfo.contractId }]
        this.$nextTick(() => {
          this.form.setFieldsValue({
            customerId: dealInfo.customerId,
            contractId: dealInfo.contractId,
            promiseDate: dealInfo.promiseDate,
          })
        })
        APILX.findShippingItem(dealInfo.contractId).then((res) => {
          console.log(res, '选择销售合同 取明细')
          let tableData = res.result
          tableData.forEach((item) => {
            item.contractItemId = item.id
            if (item.attachment) {
              let ids = item.attachment
              getFileListByIds({ ids }).then((res) => {
                if (res.code == 200) {
                  let fileList = ''
                  fileList = res.result
                  if (fileList.length > 0) {
                    item.picUrl = this.domianURL + fileList[0].uri
                    this.tableData.push(item)
                  } else {
                    item.picUrl = require('../../assets/img/noPicture.jpg')
                    this.tableData.push(item)
                  }
                }
              })
            } else {
              item.picUrl = require('../../assets/img/noPicture.jpg')
              this.tableData.push(item)
            }
          })
          console.log(tableData, '0.0tableData')
          this.total = tableData.length
        })
        return
      } else if (query.dealGoods) {
        this.menus = ['销售管理', '销售合同', '合同详情']
        let dealGoods = JSON.parse(query.dealGoods)
        this.customerList = [{ customerFullName: dealGoods.customerIdText, id: dealGoods.customerId }]
        this.contractList = [{ contractName: dealGoods.contractName, id: dealGoods.contractId }]
        console.log(dealGoods.goods)
        this.total = dealGoods.goods.length
        this.$nextTick(() => {
          this.form.setFieldsValue({
            customerId: dealGoods.customerId,
            contractId: dealGoods.contractId,
            promiseDate: dealGoods.promiseDate,
          })
        })
        for (let i = 0; i < dealGoods.goods.length; i++) {
          const g = dealGoods.goods[i]
          g.shippedNum = g.num
          g.id = g.contractItemId
          g.contractId = dealGoods.contractId
          if (g.attachment) {
            let ids = g.attachment
            getFileListByIds({ ids }).then((res) => {
              if (res.code == 200) {
                let fileList = ''
                fileList = res.result
                if (fileList.length > 0) {
                  g.picUrl = this.domianURL + fileList[0].uri
                  this.tableData.push(g)
                } else {
                  g.picUrl = require('../../assets/img/noPicture.jpg')
                  this.tableData.push(g)
                }
              }
            })
          } else {
            g.picUrl = require('../../assets/img/noPicture.jpg')
            this.tableData.push(g)
          }
        }
        return
      }
      /* ----------销售合同列表申请发货带入客户、合同、日期信息end---------- */
      this.getDictModel()
    },
    selectUser(v, row) {
      this.receiveById = row.length > 0 ? row[0].id : ''
    },
    inputFocus(record) {
      const isSelect = this.selectedRowKeys.filter((each) => each == record.id)
      if (isSelect.length == 0) {
        this.tableData.forEach((itemTable, index) => {
          if (itemTable.id == record.id) {
            itemTable.shippedNum = ''
          }
        })
        this.$antdMessage.error('请先勾选当前数据')
      }
    },
    blur(e, i) {
      console.log(e, '88888')
      let newNum = fourFloatNum(e.target.value)
      let shippingNum = fourFloatNum(this.tableData[i].shippingNum)
      let saleNum = fourFloatNum(this.tableData[i].saleNum) //订购数量
      if (newNum > saleNum - shippingNum) {
        this.$antdMessage.error(`本次发货数量不能大于可发货数量(${saleNum - shippingNum})`)
        this.tableData[i].shippedNum = saleNum - shippingNum
        console.log(this.tableData[i].shippedNum, 'this.tableData[i].shippedNum')
        this.onSelectChange(this.selectedRowKeys, this.selectedRows)
        this.tableData.splice()
      } else {
        this.tableData[i].shippedNum = newNum
        this.tableData.splice()
      }
    },
    inputChange(e, i) {
      let newNum = fourFloatNum(e.target.value)
      this.tableData[i].shippedNum = newNum
      this.tableData.splice()
    },
    // table
    // 排序
    handleChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('看看这是啥33：', sorter)
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.checkBoxStatus()
      this.selectedRows = selectedRows
      if (this.selectedRowKeys.length !== 0) {
        this.selectedRowKeys.forEach((item) => {
          this.tableData.forEach((itemTable) => {
            if (itemTable.id == item) {
              if (!itemTable.shippedNum) {
                itemTable.shippedNum = itemTable.saleNum - itemTable.shippingNum
              }
            }
          })
        })
      }
    },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.selectedRows.push(item)
        }
        this.onSelectChange(this.selectedRowKeys, this.selectedRows)
      } else {
        // for (let item of this.tableData) {
        //   this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
        //     return each != item.id
        //   })
        // }
        this.selectedRowKeys = []
        this.selectedRows = []
        this.onSelectChange(this.selectedRowKeys, this.selectedRows)
      }
      this.checkBoxStatus()
    },
    // 清空
    clearArr() {
      this.selectedRowKeys = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.tableData) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    getDictModel() {
      APILX.selectCustomerList().then((res) => {
        console.log(res, '下拉客户')
        this.customerList = res.result
      })
    },
    // 客户下拉选择
    handleSelectCustomer(value) {
      console.log(value)
      this.selectByUserId(value)
      this.form.resetFields('contractId')
      this.form.resetFields('promiseDate')
      this.tableData = []
    },
    selectByUserId(id) {
      APILX.erpShippingApplySelectByUserId(id).then((res) => {
        console.log(res, '选择客户 取销售合同')
        this.contractList = res.result
      })
    },
    // 合同下拉选择
    handleSelectContract(value) {
      this.findShippingItem(value)
      let item = this.contractList.filter((each) => each.id == value)
      console.log(item, 'item0.0.0.')
      this.form.setFieldsValue({
        promiseDate: item[0].promiseDate,
      })
    },
    findShippingItem(id) {
      this.tableData = []
      APILX.findShippingItem(id).then((res) => {
        console.log(res, '选择销售合同 取明细')
        let tableData = res.result
        tableData.forEach((item) => {
          item.contractItemId = item.id
          if (item.attachment) {
            let ids = item.attachment
            getFileListByIds({ ids }).then((res) => {
              if (res.code == 200) {
                let fileList = ''
                fileList = res.result
                if (fileList.length > 0) {
                  item.picUrl = this.domianURL + fileList[0].uri
                  this.tableData.push(item)
                } else {
                  item.picUrl = require('../../assets/img/noPicture.jpg')
                  this.tableData.push(item)
                }
              }
            })
          } else {
            item.picUrl = require('../../assets/img/noPicture.jpg')
            this.tableData.push(item)
          }
        })
        console.log(tableData, '0.0tableData')
        this.total = tableData.length
        // this.tableData = tableData
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeModalUpdate()
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      // console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      this.form.validateFields((err, values) => {
        console.log(values, '表单')
      })
      if (this.selectedRowKeys.length == 0) {
        this.$antdMessage.error('请先选择数据')
        return
      }
      for (let i = 0; i < this.selectedRows.length; i++) {
        const item = this.selectedRows[i]
        if (!item.shippedNum || item.shippedNum === '0') {
          console.log(item.shippedNum)
          this.$antdMessage.error('第' + (i + 1) + '条数据的本次发货数量必填且不为0')
          return
        }
      }
      if (e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.handleSubmit(e)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    // 提交
    handleSubmit(processDataVo) {
      this.form.validateFields((err, values) => {
        if (!err) {
          let parameters = {
            ...values,
            erpShippingApplyItemSaveDtoList: this.selectedRows,
            attachment: this.attachment,
            processDataVo: processDataVo,
          }
          parameters.receiveBy = this.receiveById
          this.loadingSubmit = true
          APILX.erpShippingApplyAdd(parameters).then((res) => {
            if (res.code == 200) {
              this.loadingSubmit = false
              this.$antdMessage.success('申请发货成功！')
              this.$emit('refresh')
              this.goBack()
            } else {
              this.loadingSubmit = false
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
    cancel() {},
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 55px);
  overflow-y: scroll;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}
.imgClass {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}
</style>
